//
//  SliderBannerView.m
//  HAHAWENWAN
//
//  Created by xiaowu on 2017/10/16.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "SliderBannerView.h"
#import "SliderBannerItemCell.h"

@interface SliderBannerView ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray <SliderBannerItem *> *dataSource;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIImage *placeHolderImage;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) BOOL loop;

@property (nonatomic, strong) UILabel *indexLabel;
@end

@implementation SliderBannerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = [NSMutableArray array];
        _placeHolderImage = [UIImage imageNamed:@""];
        _loop = NO;
        [self configureUI];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.collectionView.frame = self.bounds;
    
    self.indexLabel.frame = CGRectMake(self.width - 15 - self.indexLabel.width, self.height - 10 - self.indexLabel.height, self.indexLabel.width, 20);
    
}

#pragma mark - Method
- (void)setDataSource:(NSArray <SliderBannerItem *> *)dataSource withDelegate:(id <SliderBannerViewDelegate>)delegate withPlaceHolder:(UIImage *)image infiniteLoop:(BOOL)loop {
    self.loop = loop;
    if (loop) {
        [self configureInfiniteLoop:dataSource];
    } else {
        self.dataSource = [NSMutableArray arrayWithArray:dataSource];
    }
    self.delegate = delegate;
    self.placeHolderImage = image;
    
    [self.collectionView reloadData];
    // 处理选中index 初始位置1
    [self scrollIndexOrSelectIndex:[self getSelectIndex:1]];
    // 处理循环
    [self scrollViewWithLoop:1];
}

- (void)configureUI {
    [self addSubview:self.collectionView];
    [self addSubview:self.indexLabel];
}

- (void)configureInfiniteLoop:(NSArray <SliderBannerItem *> *)dataSource {
    if (dataSource.count > 1) {
        NSMutableArray *data = [NSMutableArray arrayWithArray:dataSource];
        SliderBannerItem *firstItem = dataSource.firstObject;
        SliderBannerItem *lastItem = dataSource.lastObject;
        
        [data insertObject:lastItem atIndex:0];
        [data addObject:firstItem];
        
        self.dataSource = [NSMutableArray arrayWithArray:data];
    } else {
        self.dataSource = [NSMutableArray arrayWithArray:dataSource];
    }
}

// get select index
- (NSInteger)getSelectIndex:(NSInteger)index {
    if (self.loop) {
        if (self.dataSource.count > 1) {
            if (index == 0) {
                return self.dataSource.count - 1 - 2;
            } else if (index == self.dataSource.count - 1) {
                return 0;
            } else {
                return index - 1;
            }
        } else {
            return index;
        }
    }
    return index;
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    SliderBannerItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"itemCell" forIndexPath:indexPath];
    
    SliderBannerItem *item = [self.dataSource safeObjectAtIndex:indexPath.row];
    cell.Type = item.isVideo ? SliderBannerItemCellTypeForVideo : SliderBannerItemCellTypeForNormal;

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:item.imageUrl] placeholderImage:self.placeHolderImage changeContentModel:UIViewContentModeScaleAspectFill];
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:item.imageUrl] placeholderImage:self.placeHolderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//        
//    }];
    cell.block = ^{
        if ([weakSelf.delegate respondsToSelector:@selector(sliderBannerView:clickIndex:)]) {
            [weakSelf.delegate sliderBannerView:weakSelf playButtonClickIndex:[weakSelf getSelectIndex:indexPath.row]];
        }
    };
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.width, self.height);
}

#pragma mark - UICollectionDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(sliderBannerView:clickIndex:)]) {
        [self.delegate sliderBannerView:self clickIndex:[self getSelectIndex:indexPath.row]];
    }
}

#pragma mark - UIScrollViewDeleagte

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat x = scrollView.contentOffset.x;
    CGFloat page = x / self.width;
    NSInteger index = (page + 0.3) / 1;
    
    [self scrollIndexOrSelectIndex:[self getSelectIndex:index]];
    // 处理循环
    [self scrollViewWithLoop:index];
    
    NSLog(@"scrollViewDidEndDecelerating: %f, index:%ld", page, (long)index);
}

- (void)scrollIndexOrSelectIndex:(NSInteger)index {
    if (self.loop) {
        if (self.dataSource.count == 1) {
            self.index = index;
            [self.indexLabel setText:[NSString stringWithFormat:@" 1/1 "]];
        } else {
            [self.indexLabel setText:[NSString stringWithFormat:@" %ld/%ld ", index + 1, self.dataSource.count - 2]];
        }
    } else {
        self.index = index;
        [self.indexLabel setText:[NSString stringWithFormat:@" %ld/%ld ", index + 1, self.dataSource.count]];
    }
    
    NSDictionary *attributes = @{NSFontAttributeName:self.indexLabel.font};
    CGFloat length = [self.indexLabel.text boundingRectWithSize:CGSizeMake(ScreenWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
    length = ceilf(length);
    self.indexLabel.width = length;
    [self layoutSubviews];
}

- (void)scrollViewWithLoop:(NSInteger)index {
    if (!self.loop) {
        return;
    }
    if (index == 0) {
        [self.collectionView scrollRectToVisible:CGRectMake(self.width * (self.dataSource.count - 2), 0, self.collectionView.width, self.collectionView.height) animated:NO];
    } else if (index == (self.dataSource.count - 1)) {
        [self.collectionView scrollRectToVisible:CGRectMake(self.width * 1, 0, self.collectionView.width, self.collectionView.height) animated:NO];
    } else {
        [self.collectionView setMj_offsetX:(self.width * index)];

//        [self.collectionView scrollRectToVisible:CGRectMake(self.width * index, 0, self.collectionView.width, self.collectionView.height) animated:NO];
    }
}

#pragma mark - Getters
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = self.bounds.size;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 横向
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.bounces = NO;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SliderBannerItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"itemCell"];
    }
    return _collectionView;
}

- (UILabel *)indexLabel {
    if (!_indexLabel) {
        _indexLabel = [[UILabel alloc] init];
        _indexLabel.font = TextPingFangFontSize(14);
        _indexLabel.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.5];
        _indexLabel.textColor = [UIColor whiteColor];
        _indexLabel.clipsToBounds = YES;
        _indexLabel.height = 20;
        _indexLabel.layer.cornerRadius = _indexLabel.height * 0.5;
    }
    return _indexLabel;
}

@end
